import getStorage from './getStorage.js'
import basePath from './basePath.js'
import basePath2 from './basePath2.js'
import needProxy from './needProxy.js'
import store from '../store'
import Vue from 'vue'

let tokenError = false
let resHandler = (url, option, res) => {
	if(option.ifFile){
		return
	}
	console.debug('printApiRes', {
		url,
		option,
		res
	})
	if(!option.noErrorMsg){
		var errorMsg = '';
		if (res.code != 0 && res.code != 200 && res.code != 401 && res.msg) {
			errorMsg = res.msg
		}
		if (res.status && res.error) {
			errorMsg = res.error
		}
		if (errorMsg){
			setTimeout(()=>{
				uni.showToast({
					title: errorMsg,
					icon: 'none'
				})
			})
		}
	}
	if (!needProxy && res.code == 401 && url.indexOf('/krt-data/api/dataopt/v1/actLog/') === -1) {
		uni.$emit('logout-' + option.pageCid)
		Vue.prototype.$afterTokenError(option)
	}
}

export default option => {
	return new Promise((resolve, reject) => {
		option = Object.assign({
			method: 'post',
			data: {},
			header: {
				'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
			}
		}, option);
		var url, ifProxy = false,
			method = option.method,
			header = option.header,
			data = option.data;
		// 如果是非模块化接口，是项目实际的接口，则加上配置信息里的接口基础路径
		if (!option.moduleUrl && !/^https?:\/\//.test(option.url)) {
			var appInfo = store.state.$appInfo;
			var development = store.state.$development;
			if (appInfo.basePath && appInfo.basePath.length > 0) {
				if (typeof option.basePathIdx === 'number' && appInfo.basePath[option.basePathIdx]) {
					option.url = appInfo.basePath[option.basePathIdx][development] + option.url
				} else if (typeof appInfo.defaultPath === 'number' && appInfo.basePath[appInfo.defaultPath]) {
					option.url = appInfo.basePath[appInfo.defaultPath][development] + option.url
				}
			}
		}
		if(/^http:\/\//.test(option.url)){
			option.url = option.url.replace('http','https')
		}
		// 项目实际接口，都会带上http开头
		if (/^https?:\/\//.test(option.url)) {
			ifProxy = needProxy
			// 如果是发布到编辑器中，则需要代理，如果是应用到实际项目中，则不需要代理
			if (ifProxy) {
				if(option.method.toLowerCase() === 'post'){
					if(option.header['Content-Type'].indexOf('x-www-form-urlencoded') > -1){
						url = basePath2 + '/form';
						var dataStr = '';
						for (var key in option.data) {
							if (dataStr === '') {
								dataStr += key + '=' + option.data[key]
							} else {
								dataStr += '&' + key + '=' + option.data[key]
							}
						}
						option.data = dataStr
					}else {
						url = basePath2 + '/post';
						option.data = JSON.stringify(option.data)
					}
				}else if(option.method.toLowerCase() === 'get'){
					url = basePath2 + '/get';
					var dataStr = '';
					for (var key in option.data) {
						if (dataStr === '') {
							dataStr += key + '=' + option.data[key]
						} else {
							dataStr += '&' + key + '=' + option.data[key]
						}
					}
					if(dataStr !== ''){
						if(option.url.indexOf('?') === -1){
							option.url += '?' + dataStr
						}else{
							option.url += '&' + dataStr
						}
					}
					option.data = undefined
				}
				method = 'POST';
				header = {
					'Content-Type': 'application/json;charset=utf-8'
				};
				if(getStorage('token')){
					option.header.Authorization = getStorage('token')
				}
				data = {
					header: option.header,
					params: option.data,
					url: option.url
				}
				url += '?t=' + new Date().getTime()
				// 这里往上，得出的url、header、data、method用于请求代理接口
			} else {
				// 这里用于实际项目中直接请求项目接口
				url = option.url
				if(option.needAuth){
					header.Authorization = getStorage('token') || ''
				}
			}
		} else {
			// 这里用于请求模块化接口，如获取版本信息，获取页面json等
			url = basePath + option.url
		}
		uni.request({
			url,
			method,
			header,
			data,
			success(res) {
				res = res.data;
				if (!ifProxy) {
					resHandler(url, option, res)
					resolve(res)
				} else {
					var newRes = JSON.parse(res.data);
					resHandler(url, option, newRes)
					resolve(newRes)
				}
			},
			fail(ret) {
				reject(ret)
			}
		})
	})
}
